Last updated: February 9 Tuesday 2021
Dynamically import a method in a file, from a string
📋
from importlib import import_module
my_module = 'django.contrib.sessions.backends.cache.SessionStore'
import_module(my_module)
Check file exists or not
📋
from os import path
path = '/xx/xx'
path.exists(path)
Inspecting current function
📋
import inspect
from pprint import pprint
pprint(inspect.currentframe().f_locals)
Getting datetime in UTC format
📋
from datetime import datetime, timezone
int(datetime.now(timezone.utc).timestamp())
1603848107
Adding/Subracting timedelta
📋
from datetime import datetime, timedelta
current = datetime.now()
delta = timedelta(days=0 , seconds=5 , microseconds=0 , milliseconds=0 , minutes=0 , hours=0 , weeks=0 )
five_second_plus_current = current + delta
Printing very large numbers (python3)
📋
one_hundred_thousand = 100 _000
one_million = 1 _000_000
total = one_hundred_thousand + one_million
print(f'{total:,} ' )
Using context managers for managing resources (like files, database connections)
📋
with open('test.txt' , 'r' ) as f:
file_content = f.read()
words = file_content.split(' ' )
word_count = len(words)
print(word_count)
Usiing enumerate function
📋
names = ['Corey' , 'Ali' , 'John' , 'David' ]
for index, name in enumerate(names):
print(index, name)
for index, name in enumerate(names, start=1 ):
print(index, name)
Using zip function
📋
names = ['Peter parker' , 'Barry' , 'Klark' ]
heroes = ['Spider man' , 'Flash' , 'Superman' ]
for name, hero in zip(names, heroes):
print('f{name} is {hero}' )
Using _ for unused variables
📋
Doing unpacking the tuple / list
📋
a, b, c = (1 , 2 , 3 , 4 )
a, b, *c = (1 , 2 , 3 , 4 )
a, b, *_ = (1 , 2 , 3 , 4 )
a, b, *c, d = (1 , 2 , 3 , 4 , 5 )
print(a)
print(b)
print(c)
print(d)
1
2
[3 , 4 ]
5
Using setattr and getattr method
📋
class Person () :
pass
person = Person()
perosn_info = {'first' : 'Corey' , 'last' : 'Anderson' }
for key, value in person_info.items():
setattr(person, key, value)
for key in person_info.keys():
print(getattr(person, key))
Getting secret info like password from terminal
📋
from getpass import getpass
name = input('Enter your name: ' )
password = getpass('Enter your password: ' )
print('Logging in ....' )
Using -m to run the python modules that exist in the directory listed in sys.PATH
📋
Using help() function to get help
📋
Using dir() function to list down all the attributes and functions
📋
from datetime import datetime
dir(datetime)
Using lambda function
Using map function
Using filter function
Using reduce function
Using displayhook to format your output
You can simply format your output just using the displayhook property available in sys module
It will work only in Python Interactive Mode. It will not change the functionality of print function
📋
import sys
def my_display (x) :
print('We are going to display output: ' )
print(x)
sys.displayhook = my_display
x = 92
x
We are going to display output
92
Redirections